package com.lagou.homework.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

/**
 *
 *
 * 从RpcContext获取IP并打印到控制台，正确打印IP
 */
@Service(timeout = 50000)
@Component
public class HelloServiceImpl implements HelloService{

    @Override
    public String hello(String world, int i) {
        System.out.println("请求B的IP地址为："+
                RpcContext.getContext().getAttachment("ip"));
        return "hello:"+world;
    }

    @Override
    public String methodA() {
        sleep();
        return "this is methodA";
    }

    @Override
    public String methodB() {
        sleep();
        return "this is methodB";
    }

    @Override
    public String methodC() {
        sleep();
        return "this is methodC";
    }

    private void sleep() {
        try {
            Thread.sleep(getRandomInt(300));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private int getRandomInt(int random) {
        return ThreadLocalRandom.current().nextInt(random);
    }
}
